#!/usr/bin/env python
# -*- coding: utf-8 -*-
import plistlib
import os, shutil, sys, getopt
import cPickle
import urllib

def main():
	opts, args = getopt.getopt(sys.argv[1:], 'f:p:o:')

	library = playlists = outpath = ''
	for o, a in opts:
		if o == '-f': library = a
		if o == '-p': playlists = a
		if o == '-o': outputdir = a

	if not library:
		library = os.path.join(os.environ.get('HOME'), 'Music/iTunes/iTunes Music Library.xml')

	if library.endswith('.xml'):
		p = plistlib.PlistParser()
		p.parse(open(library))
		p = p.root
		cPickle.dump(p, open(library + '.pickle', 'w', 1))
	else: # pickle
		p = cPickle.load(open(library))

	playlists = playlists.split(':')
	for playlist in p['Playlists']:
		if playlist['Name'] in playlists:
			outdir = os.path.join(outputdir, playlist['Name'])
			os.makedirs(outdir)
			m3u = open(os.path.join(outdir, playlist['Name'] + '.m3u'), 'w')
			for track in playlist['Playlist Items']:
				track = p['Tracks']['%s' % track['Track ID']]
				filename = urllib.unquote(track['Location'][16:]) # temporaire (pour virer file://localhost)
				shutil.copy(filename, outdir)
				#m3u.write("#EXTINF:%s %s\n" % (track['Total Time'], track['Name']))
				m3u.write("%s\n" % os.path.basename(filename))
			m3u.close()
				

if __name__ == '__main__':
	main()
